{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1. OGR矢量数据参考网站\n",
    "- [www.osgeo.cn/gdal](https://www.osgeo.cn/gdal/programs/index.html)\n",
    "- [https://www.osgeo.cn/pygis/ogr-intro.html](https://www.osgeo.cn/pygis/ogr-intro.html)\n",
    "- [gdal.org](https://gdal.org/index.html)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2. OGR的数据驱动\n",
    "- [Vector drivers](https://gdal.org/drivers/vector/index.html)\n",
    "\n",
    "## 2.1. 列出ogr所有的矢量驱动数据类型名称\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#coding=utf-8\n",
    "from osgeo import ogr,gdal,osr #导入ogr包\n",
    "import os\n",
    "gdal.SetConfigOption(\"GDAL_FILENAME_IS_UTF8\", \"YES\") #中文乱码问题\n",
    "gdal.SetConfigOption(\"SHAPE_ENCODING\", \"GBK\")\n",
    "#set the proj dir 投影数据目录设置\n",
    "os.environ['PROJ_LIB'] = r'.venv\\Lib\\site-packages\\osgeo\\data\\proj'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "76\n",
      "['FITS']\n",
      "['PCIDSK', 'netCDF', 'PDS4', 'VICAR', 'JP2OpenJPEG']\n",
      "['PDF', 'MBTiles', 'BAG', 'EEDA', 'OGCAPI']\n",
      "['ESRI Shapefile', 'MapInfo File', 'UK .NTF', 'LVBAG', 'OGR_SDTS']\n",
      "['S57', 'DGN', 'OGR_VRT', 'Memory', 'CSV']\n",
      "['GML', 'GPX', 'LIBKML', 'KML', 'GeoJSON']\n",
      "['GeoJSONSeq', 'ESRIJSON', 'TopoJSON', 'OGR_GMT', 'GPKG']\n",
      "['SQLite', 'ODBC', 'WAsP', 'PGeo', 'MSSQLSpatial']\n",
      "['PostgreSQL', 'OpenFileGDB', 'DXF', 'CAD', 'FlatGeobuf']\n",
      "['Geoconcept', 'GeoRSS', 'VFK', 'PGDUMP', 'OSM']\n",
      "['GPSBabel', 'OGR_PDS', 'WFS', 'OAPIF', 'EDIGEO']\n",
      "['SVG', 'Idrisi', 'XLS', 'ODS', 'XLSX']\n",
      "['Elasticsearch', 'Carto', 'AmigoCloud', 'SXF', 'Selafin']\n",
      "['JML', 'PLSCENES', 'CSW', 'VDV', 'MVT']\n",
      "['NGW', 'MapML', 'GTFS', 'PMTiles', 'JSONFG']\n",
      "['MiraMonVector', 'TIGER', 'AVCBin', 'AVCE00', 'HTTP']\n"
     ]
    }
   ],
   "source": [
    "cnt = ogr.GetDriverCount() ##获取驱动类型个数\n",
    "print(cnt) #打印驱动类型个数\n",
    "driverNameList=[] #定义存放驱动名称的数组\n",
    "for i in range(cnt):\n",
    "    driver = ogr.GetDriver(i)#遍历所有驱动\n",
    "    driverName = driver.GetName() #获取驱动名称\n",
    "    if not driverName in driverNameList:\n",
    "        driverNameList.append(driverName)\n",
    "    if(i%5==0): #为方便查看每5个打印一组\n",
    "        print(driverNameList)\n",
    "        driverNameList=[] #打印完清空"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.2. 通过驱动名称获取数据驱动对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['CopyDataSource',\n",
       " 'CreateDataSource',\n",
       " 'DeleteDataSource',\n",
       " 'Deregister',\n",
       " 'GetDescription',\n",
       " 'GetMetadata',\n",
       " 'GetMetadataDomainList',\n",
       " 'GetMetadataItem',\n",
       " 'GetMetadata_Dict',\n",
       " 'GetMetadata_List',\n",
       " 'GetName',\n",
       " 'Open',\n",
       " 'Register',\n",
       " 'SetDescription',\n",
       " 'SetMetadata',\n",
       " 'SetMetadataItem',\n",
       " 'TestCapability',\n",
       " '__class__',\n",
       " '__delattr__',\n",
       " '__dict__',\n",
       " '__dir__',\n",
       " '__doc__',\n",
       " '__eq__',\n",
       " '__firstlineno__',\n",
       " '__format__',\n",
       " '__ge__',\n",
       " '__getattribute__',\n",
       " '__getstate__',\n",
       " '__gt__',\n",
       " '__hash__',\n",
       " '__init__',\n",
       " '__init_subclass__',\n",
       " '__le__',\n",
       " '__lt__',\n",
       " '__module__',\n",
       " '__ne__',\n",
       " '__new__',\n",
       " '__reduce__',\n",
       " '__reduce_ex__',\n",
       " '__repr__',\n",
       " '__setattr__',\n",
       " '__sizeof__',\n",
       " '__static_attributes__',\n",
       " '__str__',\n",
       " '__subclasshook__',\n",
       " '__weakref__',\n",
       " 'name',\n",
       " 'this',\n",
       " 'thisown']"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "driver = ogr.GetDriverByName('ESRI Shapefile')\n",
    "dir(driver) #列出driver的所有方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ESRI Shapefile\n"
     ]
    }
   ],
   "source": [
    "print(driver.GetDescription())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.3. 打开数据Open()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "data\\Search_Polygon.shp\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\GitHub\\py313Env\\.venv\\Lib\\site-packages\\osgeo\\ogr.py:601: FutureWarning: Neither ogr.UseExceptions() nor ogr.DontUseExceptions() has been explicitly called. In GDAL 4.0, exceptions will be enabled by default.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "shp=r\"data\\Search_Polygon.shp\"\n",
    "ds = driver.Open(shp)\n",
    "print(ds.GetDescription())\n",
    "ds.Destroy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "# 3. 数据源osgeo.ogr.DataSource"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.1. 矢量数据的datasource"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dataSource: ['AbortSQL', 'Close', 'CommitTransaction', 'CopyLayer', 'CreateLayer', 'DeleteLayer', 'Dereference', 'Destroy', 'ExecuteSQL', 'FlushCache', 'GetDescription', 'GetDriver', 'GetLayer', 'GetLayerByIndex', 'GetLayerByName', 'GetLayerCount', 'GetMetadata', 'GetMetadataDomainList', 'GetMetadataItem', 'GetMetadata_Dict', 'GetMetadata_List', 'GetName', 'GetRefCount', 'GetStyleTable', 'GetSummaryRefCount', 'Reference', 'Release', 'ReleaseResultSet', 'RollbackTransaction', 'SetDescription', 'SetMetadata', 'SetMetadataItem', 'SetStyleTable', 'StartTransaction', 'SyncToDisk', 'TestCapability', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__firstlineno__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__static_attributes__', '__str__', '__subclasshook__', '__swig_destroy__', '__weakref__', '_add_layer_ref', '_invalidate_layers', 'name', 'this', 'thisown']\n",
      "----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n",
      "Description(): data\\Search_Polygon.shp\n"
     ]
    }
   ],
   "source": [
    "shapefile = r\"data\\Search_Polygon.shp\"\n",
    "driver = ogr.GetDriverByName(\"ESRI Shapefile\")\n",
    "ds = driver.Open(shapefile, 0) #打开数据# 0 means read-only. 1 means writeable.\n",
    "print(\"dataSource:\",dir(ds)) #查看dataSource的属性和方法\n",
    "print(20*'-----------')\n",
    "print(\"Description():\",ds.GetDescription()) #dataSource的描述信息\n",
    "ds.Destroy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.2. 通过拷贝数据源实现shp转geojson"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "data\\Search_Polygon.json\n",
      "data\\Search_Polygon.json was copied by driver.CopyDataSource\n"
     ]
    }
   ],
   "source": [
    "shp = r\"data\\Search_Polygon.shp\" #SHP数据路径\n",
    "json = r'data\\Search_Polygon.json' #输出的json文件路径\n",
    "shp_driver = ogr.GetDriverByName('ESRI Shapefile') # shp数据的数据驱动\n",
    "shp_ds = shp_driver.Open(shp, 0) # 0 means read-only. 1 means writeable.\n",
    "json_driver = ogr.GetDriverByName('GeoJSON') # json文件的数据驱动\n",
    "if os.path.exists(json): #判断是否已存在，如果有则删除\n",
    "        json_driver.DeleteDataSource(json)\n",
    "json_ds=json_driver.CopyDataSource(shp_ds,json) #将shp文件的数据源拷贝到 json的数据源中\n",
    "shp_ds.Destroy() #释放内存\n",
    "print(json_ds.GetDescription()) #测试输出json的数据源的文件描述信息\n",
    "json_ds.Destroy() #释放内存\n",
    "print(json+' was copied by driver.CopyDataSource')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "# 4. 图层layer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['AlterFieldDefn', 'AlterGeomFieldDefn', 'Clip', 'CommitTransaction', 'CreateFeature', 'CreateField', 'CreateFieldFromArrowSchema', 'CreateFieldFromPyArrowSchema', 'CreateFields', 'CreateGeomField', 'DeleteFeature', 'DeleteField', 'Dereference', 'Erase', 'ExportArrowArrayStreamPyCapsule', 'FindFieldIndex', 'GetArrowArrayStreamInterface', 'GetArrowStream', 'GetArrowStreamAsNumPy', 'GetArrowStreamAsPyArrow', 'GetDataset', 'GetDescription', 'GetExtent', 'GetExtent3D', 'GetFIDColumn', 'GetFeature', 'GetFeatureCount', 'GetFeaturesRead', 'GetGeomType', 'GetGeometryColumn', 'GetGeometryTypes', 'GetLayerDefn', 'GetMetadata', 'GetMetadataDomainList', 'GetMetadataItem', 'GetMetadata_Dict', 'GetMetadata_List', 'GetName', 'GetNextFeature', 'GetRefCount', 'GetSpatialFilter', 'GetSpatialRef', 'GetStyleTable', 'GetSupportedSRSList', 'Identity', 'Intersection', 'IsArrowSchemaSupported', 'IsPyArrowSchemaSupported', 'Reference', 'Rename', 'ReorderField', 'ReorderFields', 'ResetReading', 'RollbackTransaction', 'SetActiveSRS', 'SetAttributeFilter', 'SetDescription', 'SetFeature', 'SetIgnoredFields', 'SetMetadata', 'SetMetadataItem', 'SetNextByIndex', 'SetSpatialFilter', 'SetSpatialFilterRect', 'SetStyleTable', 'StartTransaction', 'SymDifference', 'SyncToDisk', 'TestCapability', 'Union', 'Update', 'UpdateFeature', 'UpsertFeature', 'WriteArrow', 'WriteArrowBatch', 'WriteArrowSchemaAndArrowArrayCapsule', 'WriteArrowStreamCapsule', 'WritePyArrow', '__arrow_c_stream__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__firstlineno__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__static_attributes__', '__str__', '__subclasshook__', '__weakref__', 'schema', 'this', 'thisown']\n"
     ]
    }
   ],
   "source": [
    "shapefile = r\"data\\Search_Polygon.shp\" # 数据文件路径\n",
    "driver = ogr.GetDriverByName(\"ESRI Shapefile\") #获取数据驱动\n",
    "ds = driver.Open(shapefile, 0) # 获取指定文件数据驱动中的数据源 # 0 means read-only. 1 means writeable.\n",
    "layer = ds.GetLayer() #获取数据源中的图层\n",
    "print(dir(layer)) #列出图层的所有方法\n",
    "ds.Destroy() # 销毁ds对象"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.1. Feature Count 　&　GetExtent　＆　GetSpatialRef"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of features is: 7\n",
      "Extent is: (111.9365567058171, 115.34495058134938, 29.53589572144047, 31.788232616034584)\n",
      "SpatialRef is: GEOGCS[\"WGS 84\",\n",
      "    DATUM[\"WGS_1984\",\n",
      "        SPHEROID[\"WGS 84\",6378137,298.257223563,\n",
      "            AUTHORITY[\"EPSG\",\"7030\"]],\n",
      "        AUTHORITY[\"EPSG\",\"6326\"]],\n",
      "    PRIMEM[\"Greenwich\",0,\n",
      "        AUTHORITY[\"EPSG\",\"8901\"]],\n",
      "    UNIT[\"degree\",0.0174532925199433,\n",
      "        AUTHORITY[\"EPSG\",\"9122\"]],\n",
      "    AXIS[\"Latitude\",NORTH],\n",
      "    AXIS[\"Longitude\",EAST],\n",
      "    AUTHORITY[\"EPSG\",\"4326\"]]\n",
      "GetMetadata is: {'DBF_DATE_LAST_UPDATE': '2022-05-15'}\n",
      "GetLayerDefn is: ['AddFieldDefn', 'AddGeomFieldDefn', 'DeleteGeomFieldDefn', 'Destroy', 'GetFieldCount', 'GetFieldDefn', 'GetFieldIndex', 'GetGeomFieldCount', 'GetGeomFieldDefn', 'GetGeomFieldIndex', 'GetGeomType', 'GetName', 'GetReferenceCount', 'IsGeometryIgnored', 'IsSame', 'IsStyleIgnored', 'SetGeomType', 'SetGeometryIgnored', 'SetStyleIgnored', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__firstlineno__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__static_attributes__', '__str__', '__subclasshook__', '__swig_destroy__', '__weakref__', 'this', 'thisown']\n"
     ]
    }
   ],
   "source": [
    "shapefile = r\"data\\Search_Polygon.shp\"\n",
    "driver = ogr.GetDriverByName('ESRI Shapefile')\n",
    "ds = driver.Open(shapefile, 0) # 0 means read-only. 1 means writeable.\n",
    "layer = ds.GetLayer()\n",
    "featureCount = layer.GetFeatureCount()\n",
    "print(\"Number of features is: %d\" %featureCount) #要素个数\n",
    "print(\"Extent is: {}\".format(layer.GetExtent())) #空间范围\n",
    "print(\"SpatialRef is: {}\".format(layer.GetSpatialRef())) #空间参考信息\n",
    "print(\"GetMetadata is: {}\".format(layer.GetMetadata())) #元数据信息\n",
    "print(\"GetLayerDefn is: {}\".format(dir(layer.GetLayerDefn())))\n",
    "ds.Destroy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.2. 图层属性LayerDefn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['AddFieldDefn', 'AddGeomFieldDefn', 'DeleteGeomFieldDefn', 'Destroy', 'GetFieldCount', 'GetFieldDefn', 'GetFieldIndex', 'GetGeomFieldCount', 'GetGeomFieldDefn', 'GetGeomFieldIndex', 'GetGeomType', 'GetName', 'GetReferenceCount', 'IsGeometryIgnored', 'IsSame', 'IsStyleIgnored', 'SetGeomType', 'SetGeometryIgnored', 'SetStyleIgnored', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__firstlineno__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__static_attributes__', '__str__', '__subclasshook__', '__swig_destroy__', '__weakref__', 'this', 'thisown']\n"
     ]
    }
   ],
   "source": [
    "shapefile = r\"data\\Search_Polygon.shp\"\n",
    "driver = ogr.GetDriverByName('ESRI Shapefile')\n",
    "ds = driver.Open(shapefile, 0) # 0 means read-only. 1 means writeable.\n",
    "layer = ds.GetLayer()\n",
    "layerDefn = layer.GetLayerDefn()\n",
    "print(dir(layerDefn))\n",
    "ds.Destroy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.3. 获取图层中的属性字段个数GetFieldCount"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of field is: 3\n"
     ]
    }
   ],
   "source": [
    "shapefile = r\"data\\Search_Polygon.shp\"\n",
    "driver = ogr.GetDriverByName('ESRI Shapefile')\n",
    "ds = driver.Open(shapefile, 0) # 0 means read-only. 1 means writeable.\n",
    "layer = ds.GetLayer()\n",
    "layerDefn = layer.GetLayerDefn()\n",
    "print(\"Number of field is: %d\" %layerDefn.GetFieldCount())\n",
    "ds.Destroy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.4. 获取属性字段的属性 GetFieldDefn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of field is: 3\n",
      "FieldDefn is: ['Destroy', 'GetAlternativeName', 'GetAlternativeNameRef', 'GetComment', 'GetDefault', 'GetDomainName', 'GetFieldTypeName', 'GetJustify', 'GetName', 'GetNameRef', 'GetPrecision', 'GetSubType', 'GetTZFlag', 'GetType', 'GetTypeName', 'GetWidth', 'IsDefaultDriverSpecific', 'IsIgnored', 'IsNullable', 'IsUnique', 'SetAlternativeName', 'SetComment', 'SetDefault', 'SetDomainName', 'SetIgnored', 'SetJustify', 'SetName', 'SetNullable', 'SetPrecision', 'SetSubType', 'SetTZFlag', 'SetType', 'SetUnique', 'SetWidth', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__firstlineno__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__static_attributes__', '__str__', '__subclasshook__', '__swig_destroy__', '__weakref__', 'justify', 'name', 'precision', 'this', 'thisown', 'type', 'width']\n",
      "----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n",
      "FieldName is: Id\n",
      "FieldWidth is: 6\n",
      "FieldType is: Integer\n",
      "FieldtPrecision is: 0\n",
      "FieldName is: name\n",
      "FieldWidth is: 50\n",
      "FieldType is: String\n",
      "FieldtPrecision is: 0\n",
      "FieldName is: code\n",
      "FieldWidth is: 50\n",
      "FieldType is: String\n",
      "FieldtPrecision is: 0\n"
     ]
    }
   ],
   "source": [
    "shapefile = r\"data\\Search_Polygon.shp\"\n",
    "driver = ogr.GetDriverByName('ESRI Shapefile')\n",
    "ds = driver.Open(shapefile, 0) # 0 means read-only. 1 means writeable.\n",
    "layer = ds.GetLayer()\n",
    "layerDefn = layer.GetLayerDefn()\n",
    "print(\"Number of field is: %d\" %layerDefn.GetFieldCount())\n",
    "print(\"FieldDefn is: %s\" %dir(layerDefn.GetFieldDefn(0)))\n",
    "print(20*'--------------')\n",
    "for i in range(layerDefn.GetFieldCount()): #遍历所有字段\n",
    "    fieldDefn = layerDefn.GetFieldDefn(i)  #获取每一个字段的属性\n",
    "    print(\"FieldName is: {}\".format(fieldDefn.GetName())) #字段名称\n",
    "    print(\"FieldWidth is: {}\".format(fieldDefn.GetWidth())) #字段长度\n",
    "    print(\"FieldType is: {}\".format(fieldDefn.GetTypeName())) #字段类型名称\n",
    "    print(\"FieldtPrecision is: {}\".format(fieldDefn.GetPrecision())) # 字段精度，用于int,double,float等数字类型\n",
    "ds.Destroy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 5. 要素 Feature"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Clone', 'Dereference', 'Destroy', 'DumpReadable', 'DumpReadableAsString', 'Equal', 'ExportToJson', 'FillUnsetWithDefault', 'GetDefnRef', 'GetFID', 'GetField', 'GetFieldAsBinary', 'GetFieldAsDateTime', 'GetFieldAsDouble', 'GetFieldAsDoubleList', 'GetFieldAsISO8601DateTime', 'GetFieldAsInteger', 'GetFieldAsInteger64', 'GetFieldAsInteger64List', 'GetFieldAsIntegerList', 'GetFieldAsString', 'GetFieldAsStringList', 'GetFieldCount', 'GetFieldDefnRef', 'GetFieldIndex', 'GetFieldType', 'GetGeomFieldCount', 'GetGeomFieldDefnRef', 'GetGeomFieldIndex', 'GetGeomFieldRef', 'GetGeometryRef', 'GetNativeData', 'GetNativeMediaType', 'GetStyleString', 'IsFieldNull', 'IsFieldSet', 'IsFieldSetAndNotNull', 'Reference', 'SetFID', 'SetField', 'SetFieldBinary', 'SetFieldBinaryFromHexString', 'SetFieldDoubleList', 'SetFieldInteger64', 'SetFieldInteger64List', 'SetFieldIntegerList', 'SetFieldNull', 'SetFieldString', 'SetFieldStringList', 'SetFrom', 'SetFromWithMap', 'SetGeomField', 'SetGeomFieldDirectly', 'SetGeometry', 'SetGeometryDirectly', 'SetNativeData', 'SetNativeMediaType', 'SetStyleString', 'UnsetField', 'Validate', '_SetField2', '_SetFieldBinary', '__class__', '__cmp__', '__copy__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__firstlineno__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__static_attributes__', '__str__', '__subclasshook__', '__swig_destroy__', '__weakref__', '_add_geom_ref', '_getfieldindex', '_invalidate_geom_refs', 'geometry', 'items', 'keys', 'this', 'thisown']\n"
     ]
    }
   ],
   "source": [
    "shapefile = r\"data\\Search_Polygon.shp\" # 数据文件路径\n",
    "driver = ogr.GetDriverByName(\"ESRI Shapefile\") #获取数据驱动\n",
    "ds = driver.Open(shapefile, 0) # 获取指定文件数据驱动中的数据源 # 0 means read-only. 1 means writeable.\n",
    "layer = ds.GetLayer() #获取数据源中的图层\n",
    "feature = layer.GetFeature(0) #获取第一个要素的属性\n",
    "print(dir(feature)) #列出图层的所有方法\n",
    "ds.Destroy() # 销毁ds对象"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.1. 遍历并获取要素的几何与属性信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "POLYGON ((114.438218128153 30.6810260580518,114.545660214002 31.6180540115831,115.344950581349 31.5512636439155,115.22863537955 30.6148787543077,114.438218128153 30.6810260580518))\n",
      "1\n",
      "A区\n",
      "42012200\n",
      "POLYGON ((113.680070706776 30.7393978595135,115.22863537955 30.6148787543077,115.098054162566 29.5358957214405,113.569042820165 29.6590870468909,113.680070706776 30.7393978595135))\n",
      "2\n",
      "B区\n",
      "42012201\n",
      "POLYGON ((112.81477139181 30.7999716158665,112.026589967986 30.849556486907,112.106797951628 31.7882326160346,112.903904538542 31.7381613585833,112.81477139181 30.7999716158665))\n",
      "3\n",
      "C区\n",
      "42012202\n",
      "POLYGON ((112.81477139181 30.7999716158665,112.903904538542 31.7381613585833,113.778975877841 31.6769950790879,113.680070706776 30.7393978595135,112.81477139181 30.7999716158665))\n",
      "4\n",
      "D区\n",
      "42012203\n",
      "POLYGON ((112.71471678183 29.7190118953811,111.936556705817 29.7680641156753,112.026589967986 30.849556486907,112.81477139181 30.7999716158665,112.71471678183 29.7190118953811))\n",
      "5\n",
      "E区\n",
      "42012204\n",
      "POLYGON ((112.71471678183 29.7190118953811,112.81477139181 30.7999716158665,113.680070706776 30.7393978595135,113.569042820165 29.6590870468909,113.552519135142 29.6603064743609,112.71471678183 29.7190118953811))\n",
      "6\n",
      "F区\n",
      "42012205\n",
      "POLYGON ((114.438218128153 30.6810260580518,113.680070706776 30.7393978595135,113.778975877841 31.6769950790879,114.545660214002 31.6180540115831,114.438218128153 30.6810260580518))\n",
      "7\n",
      "G区\n",
      "42012206\n"
     ]
    }
   ],
   "source": [
    "shapefile = r\"data\\Search_Polygon.shp\" # 数据文件路径\n",
    "driver = ogr.GetDriverByName(\"ESRI Shapefile\") #获取数据驱动\n",
    "ds = driver.Open(shapefile, 0) # 获取指定文件数据驱动中的数据源 # 0 means read-only. 1 means writeable.\n",
    "layer = ds.GetLayer() #获取数据源中的图层\n",
    "featureCount = layer.GetFeatureCount() # 获取图层中的要素个数\n",
    "for i in range(featureCount): #遍历所有要素\n",
    "    feature = layer.GetFeature(i) #获取第一个要素的属性\n",
    "    print(feature.GetGeometryRef()) #列出图层中每个要素的几何信息\n",
    "    fieldCount = feature.GetFieldCount() #属性字段的个数\n",
    "    for j in range(fieldCount): #遍历所有字段\n",
    "        print(feature.GetFieldAsString(j)) #获取所有字段的值并输出\n",
    "ds.Destroy() # 销毁ds对象"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## 5.2. 单个 Feature 转Json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'{\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[[114.43821812815277, 30.681026058051764], [114.54566021400227, 31.618054011583148], [115.34495058134938, 31.551263643915494], [115.22863537954969, 30.614878754307657], [114.43821812815277, 30.681026058051764]]]}, \"properties\": {\"Id\": 1, \"name\": \"A\\\\u533a\", \"code\": \"42012200\"}, \"id\": 0}'\n",
      "b'{\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[[113.68007070677595, 30.739397859513545], [115.22863537954969, 30.614878754307657], [115.0980541625663, 29.53589572144047], [113.5690428201648, 29.659087046890875], [113.68007070677595, 30.739397859513545]]]}, \"properties\": {\"Id\": 2, \"name\": \"B\\\\u533a\", \"code\": \"42012201\"}, \"id\": 1}'\n",
      "b'{\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[[112.8147713918105, 30.799971615866458], [112.02658996798637, 30.849556486907034], [112.10679795162815, 31.788232616034584], [112.90390453854187, 31.73816135858327], [112.8147713918105, 30.799971615866458]]]}, \"properties\": {\"Id\": 3, \"name\": \"C\\\\u533a\", \"code\": \"42012202\"}, \"id\": 2}'\n",
      "b'{\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[[112.8147713918105, 30.799971615866458], [112.90390453854187, 31.73816135858327], [113.77897587784113, 31.676995079087916], [113.68007070677595, 30.739397859513545], [112.8147713918105, 30.799971615866458]]]}, \"properties\": {\"Id\": 4, \"name\": \"D\\\\u533a\", \"code\": \"42012203\"}, \"id\": 3}'\n",
      "b'{\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[[112.71471678182985, 29.71901189538112], [111.9365567058171, 29.768064115675262], [112.02658996798637, 30.849556486907034], [112.8147713918105, 30.799971615866458], [112.71471678182985, 29.71901189538112]]]}, \"properties\": {\"Id\": 5, \"name\": \"E\\\\u533a\", \"code\": \"42012204\"}, \"id\": 4}'\n",
      "b'{\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[[112.71471678182985, 29.71901189538112], [112.8147713918105, 30.799971615866458], [113.68007070677595, 30.739397859513545], [113.5690428201648, 29.659087046890875], [113.55251913514189, 29.660306474360933], [112.71471678182985, 29.71901189538112]]]}, \"properties\": {\"Id\": 6, \"name\": \"F\\\\u533a\", \"code\": \"42012205\"}, \"id\": 5}'\n",
      "b'{\"type\": \"Feature\", \"geometry\": {\"type\": \"Polygon\", \"coordinates\": [[[114.43821812815277, 30.681026058051764], [113.68007070677595, 30.739397859513545], [113.77897587784113, 31.676995079087916], [114.54566021400227, 31.618054011583148], [114.43821812815277, 30.681026058051764]]]}, \"properties\": {\"Id\": 7, \"name\": \"G\\\\u533a\", \"code\": \"42012206\"}, \"id\": 6}'\n"
     ]
    }
   ],
   "source": [
    "shapefile = r\"data\\Search_Polygon.shp\" # 数据文件路径\n",
    "driver = ogr.GetDriverByName(\"ESRI Shapefile\") #获取数据驱动\n",
    "ds = driver.Open(shapefile, 0) # 获取指定文件数据驱动中的数据源 # 0 means read-only. 1 means writeable.\n",
    "layer = ds.GetLayer() #获取数据源中的图层\n",
    "featureCount = layer.GetFeatureCount() # 获取图层中的要素个数\n",
    "for i in range(featureCount): #遍历所有要素\n",
    "    feature = layer.GetFeature(i) #获取第一个要素的属性\n",
    "    json = feature.ExportToJson().encode('utf-8')\n",
    "    print(json)\n",
    "ds.Destroy() # 销毁ds对象"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
